package filter

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"net/http"
	"strings"
)

func RunLoginFilter() {
	var Check = func(ctx *context.Context) {
		url := ctx.Request.RequestURI
		index := strings.Index(url, "?")
		if index != -1 {
			url = Substr(url, 0, index)
		}
		if !IsCommon(url) {
			user := ctx.Input.Session("user")
			if user == nil {
				ctx.Redirect(http.StatusFound, "/static/login.html")
			}
		}
	}
	beego.InsertFilter("/*", beego.BeforeRouter, Check)
}

func IsCommon(url string) bool {
	commonUrls := []string{"/user/login", "/user/register"}
	for _, curl := range commonUrls {
		if strings.EqualFold(curl, url) {
			return true
		}
	}
	return false
}

/**安装开始位置和指定长度来截取*/
func Substr(str string, start, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0
	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length

	if start > end {
		start, end = end, start
	}

	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}
	return string(rs[start:end])
}
